<template>
  <!-- 一对多的下拉表格 -->
  <div class="select-table" ref="selectTableRef">
    <!-- 输入框, 展示  -->
    <el-input
      popper-class="select-input"
      ref="inputRef"
      @change="onChangeInput"
      v-model="value"
      placeholder="请选择"
      :suffix-icon="isShowTable ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
      @click.native="onInput($event)"
      size="mini"
      clearable
    ></el-input>
    <div ref="tableRef" class="t-table" v-if="isShowTable">
      <!-- 表格 -->
      <div v-for="(head, hIndex) in tableHead" :key="hIndex" class="col-item">
        <div class="head-label">{{ head.label }}</div>
        <el-input
          placeholder="请输入内容"
          v-model="search[head.prop]"
          @input="changeInput(search[head.prop], head.prop)"
          size="mini"
          clearable
        >
        </el-input>
        <div class="body" ref="bodyRef">
          <!-- :class="{active: !isMultiple && hIndex===tableHead.length-1 && index===currentIndex}" -->
          <div
            v-for="(item, index) in tableData[head.prop]"
            :key="index"
            class="body-item"
            :class="{ active: isActive(hIndex, index) }"
            ref="bodyItemRef"
            @click="onSelectItem(item, head.prop, hIndex, index)"
          >
            <div class="body-label" ref="bodyLabelRef">{{ item }}</div>
          </div>
        </div>
      </div>
      <!-- 脚 -->
      <!-- <div style="background: #000; width: 100%; position: absolute; bottom: 0"></div> -->
    </div>
  </div>
</template>

<script>
import { deepClone } from '@/utils';
export default {
  props: {
    // 表头
    tableHead: {
      type: Array,
      default: () => {
        return [
          {
            prop: "global",
            label: "全球港口GMP",
          },
          {
            prop: "country",
            label: "国家名称",
          },
          {
            prop: "port",
            label: "港口",
          },
        ];
      },
    },
    // 表数据
    data: {
      type: Array,
      default: () => {
        return [
          {
            id: "0001",
            global: "全球港口GMP",
            country: "全球港口GMP",
            port: "全球港口GMP",
          },
          {
            id: "00001",
            country: "中国",
            port: "南沙港",
          },
          {
            id: "00002",
            country: "中国",
            port: "黄埔港",
          },
          {
            id: "00003",
            country: "中国",
            port: "香港",
          },
        ];
      },
    },
    // 是否多选
    isMultiple: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
  },
  data() {
    return {
      isShowTable: false, // 是否显示表格
      value: "", // 输入框展示的内容
      valueList: new Set(), // 用来展示的存储数组set
      tableData: [], // 下拉框表格数据
      search: {}, // 搜索框对象
      dataInitCopy: {}, // 初始化之后的数据备份
      checkList: new Set(), // 已选择的数组的set对象,为了筛选,emit
      currentIndex: "", // 当前点击的index
    };
  },
  computed: {},
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler(v) {
        this.initData(v);
      },
    },
  },
  created() {},
  mounted() {
    document.addEventListener("click", this.closePanel, true);
  },
  beforeDestroy() {
    document.removeEventListener("click", this.closePanel, true);
  },
  methods: {
    // 展示的输入框值改变
    onChangeInput() {},
    // 点击输入框 ----控制下拉框展示与否
    onInput() {
      this.isShowTable = !this.isShowTable;
      if (this.isShowTable) this.$refs.inputRef.focus();
      else this.$refs.inputRef.blur();
    },
    // 点击下拉框别处关闭下拉框
    closePanel(e) {
      const selectTableRef = this.$refs.selectTableRef;
      // selectTableRef里是否包含点击的元素，不包含点击的元素就隐藏面板
      if (!selectTableRef.contains(e.target)) {
        this.isShowTable = false;
      }
    },
    /**
     * 修改输入框的内容
     * @param content: 输入框的内容, prop: 当前列的prop值
     */
    changeInput(content, prop) {
      // console.log(content, prop, this.search, this.dataInitCopy[prop]);
      if (content) {
        this.tableData[prop] = [...this.dataInitCopy[prop]].filter((item) => {
          console.log(item.includes(content));
          return item.includes(content);
        });
        console.log(this.tableData);
      } else {
        console.log(Array.from(this.dataInitCopy));
      }
    },
    /**
     * 点击某一个单元格
     * @params label: 单元格的内容, prop: 单元格的prop值, headIndex: 表格头的最后一个index, bodyIndex: 表格内容当前行index
     * emit: frist: 当前点击的对象, second: 已选择的对象数组
     */
    onSelectItem(label, prop, headIndex, bodyIndex) {
      if (headIndex === this.tableHead.length - 1) {
        let currentElement =
          this.$refs.bodyRef[headIndex].children[bodyIndex].firstChild;
        let arr = this.data.filter((item) => {
          return item[prop] === label;
        });
        let obj = arr.length > 0 ? arr[0] : {};
        if (this.isMultiple) {
          // 多选
          if (this.checkList.has(obj)) {
            // 如果已选择数组包含当前该选择项, 则移除类名,删除该项
            currentElement.classList.remove("active");
            this.checkList.delete(obj);
            this.valueList.delete(label);
          } else {
            // 否则添加类名并添加该项
            // currentElement.classList.value += " active";
            currentElement.classList.add("active");
            this.checkList.add(obj);
            this.valueList.add(label);
          }
          if ([...this.valueList].length > 0) {
            this.value = [...this.valueList].toString();
          }
          this.$emit("onSelect", obj, [...this.checkList]);
        } else {
          // 单选
          this.value = label;
          this.currentIndex = bodyIndex;
          this.$emit("onSelect", obj, arr);
        }
      }
    },
    // 单选时给指定元素绑定类名
    isActive(hIndex, index) {
      let flag =
        !this.isMultiple &&
        hIndex === this.tableHead.length - 1 &&
        index === this.currentIndex;
      return flag;
    },
    /**
     * 表格内容初始化的处理
     */
    initData(data) {
      if (data && data.length > 0) {
        data.map((item) => {
          this.tableHead.map((head) => {
            if (item[head.prop]) {
              let arr = this.tableData[head.prop] || [];
              arr.push(item[head.prop]);
              this.tableData[head.prop] = [...new Set(arr)];
              this.dataInitCopy[head.prop] = new Set(arr);
            }
          });
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
$border-color: #dfe6ec;
$bg-color: #f8f8f9;
@mixin check-box() {
  width: 25px;
  text-align: center;
}
.active {
  color: #409eff !important;
  background-color: #ecf5ff;
}
.select-table {
  position: relative;
  cursor: pointer;
}
.t-table {
  max-height: 350px;
  position: absolute;
  width: 100%;
  display: flex;
  margin-top: 5px;
  border: 1px solid $border-color;
  background-color: $bg-color;
  line-height: 26px;
  z-index: 9999;
  .col-item {
    flex: 1;
    font-size: 13px;
    .head-label {
      border-bottom: 1px solid $border-color;
      text-align: center;
      border-left: 1px solid $border-color;
      font-weight: bold;
      color: #515a6e;
    }
    .body {
      height: calc(100% - 55px);
      overflow: auto;
      background-color: #fff;
      .body-item {
        cursor: pointer;
      }
      &-label {
        border: 1px solid $border-color;
        border-bottom: none;
        border-right: none;
        text-align: center;
        font-size: 14px;
        color: #606266;
      }
      .body-item:last-child {
        .body-label {
          border-bottom: 1px solid $border-color;
        }
      }
    }
  }
}
</style>